package com.peng.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.base.exception.GlobalExceptionHandler;
import com.peng.base.exception.GuliException;
import com.peng.edu.entity.Subject;
import com.peng.edu.entity.excel.SubjectData;
import com.peng.edu.service.SubjectService;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    private SubjectService subjectService;

    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData==null){
            throw new GuliException(20001,"添加失败");
        }
        Subject oneSubject = this.existOneSubject(subjectData.getOneSubjectName());
        if (oneSubject==null){
            oneSubject=new Subject();
            oneSubject.setTitle(subjectData.getOneSubjectName());
            oneSubject.setParentId("0");
            subjectService.save(oneSubject);
        }
        String pid = oneSubject.getId();
        Subject twoSubject = this.existTwoSubject(subjectData.getTwoSubjectName(), pid);
        if (twoSubject==null){
            twoSubject=new Subject();
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            twoSubject.setParentId(pid);
            subjectService.save(twoSubject);
        }

    }
    //判断一级分类不能重复添加
    private Subject existOneSubject(String name){
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getTitle,name);
        queryWrapper.eq(Subject::getParentId,0);
        Subject one = subjectService.getOne(queryWrapper);
        return one;
    }

    //判断一级分类不能重复添加
    private Subject existTwoSubject(String name,String parentId){
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getTitle,name);
        queryWrapper.eq(Subject::getParentId,parentId);
        Subject one = subjectService.getOne(queryWrapper);
        return one;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
